package com.ciwong.epaper.modules.msg.ui;

import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.modules.bookstore.bean.BannerBean;
import com.ciwong.epaper.modules.epaper.bean.BasePaging;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.me.bean.MyWork;
import com.ciwong.epaper.modules.me.bean.WorkContents;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.msg.adapter.WorkMessageAdapter;
import com.ciwong.epaper.modules.msg.bean.IsDelWorkBean;
import com.ciwong.epaper.modules.msg.bean.MessageInfo;
import com.ciwong.epaper.modules.msg.bean.MsgTypeConfig;
import com.ciwong.epaper.modules.msg.dao.MsgDao;
import com.ciwong.epaper.modules.msg.dao.MsgRequest;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.widget.PullToRefreshView;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class WorkMessageActivity extends BaseActivity implements PullToRefreshView.OnHeaderRefreshListener,
        PullToRefreshView.OnFooterRefreshListener {
    private EApplication mEApplication;
    private ListView mListView;

    /**
     * 适配器
     */
    private WorkMessageAdapter workMessageAdapter;


    private List<MyWork> mLocalWorkList;


    /**
     * 发送者ID
     */
    int senderId;

    private Handler handler = new Handler();

    /**
     * 刷新ListView
     */
    private PullToRefreshView mRefreshView;
    /**
     * 默认从第一页开始加载
     */
    private final int default_page = 1;

    /**
     * 当前页码
     */
    private int curPage = default_page;
    /**
     * 默认加载数据大小
     */
    private static final int LOAD_PAGE_SIZE = 10;

    /**
     * 是否是刷新状态,true为刷新，false为加载更多
     */
    private boolean isRefresh = true;

    private String senderName;

    private int msgGroupType;

    private MessageInfo messageInfo;

    private UserInfoBase userInfoBase;

    private String mWorkId;


    protected void preCreate() {

        Intent intent = getIntent();
        if (intent != null) {
            messageInfo = (MessageInfo) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
            senderId = messageInfo.getSenderId();
            senderName = messageInfo.getSenderName();
            msgGroupType = messageInfo.getMsgGroup();
        }
    }

    @Override
    protected int setView() {
        return R.layout.activity_work_message;
    }

    @Override
    protected void findViews() {
        mListView = (ListView) findViewById(R.id.work_msg_list);
        mRefreshView = (PullToRefreshView) findViewById(R.id.work_msg_refresh_view);

    }


    @Override
    protected void initEvent() {
        workMessageAdapter = new WorkMessageAdapter(this, null, msgGroupType);
        mListView.setAdapter(workMessageAdapter);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                messageInfo = (MessageInfo) adapterView.getItemAtPosition(position);
                MessageInfo.Content content = messageInfo.getContent();
                mWorkId = content.getWordId();
                String workName = content.getWorkName();
                String href = content.getHref();
                String doWorkId = content.getDoWorkId();
                int type = messageInfo.getMsgType();

                //运营商消息跳转
                if (type == MsgTypeConfig.MSG_SERVICE || type == MsgTypeConfig.MSG_SERVICE_NEW) {
                    if (TextUtils.isEmpty(href)) {
                        return;
                    }

                    if (href.startsWith("ciwong://")) {
                        try {
                            String serviceId = href.substring(9);
                            MeJumpManager.jumpBuyService(WorkMessageActivity.this, R.string.go_back, Integer.parseInt(serviceId), -1, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY, null);

                        } catch (Exception e) {

                        }

                    } else {
                        BannerBean bannerBean = new BannerBean();
                        bannerBean.setLinkAddress(href);
                        EpaperJumpManager.jumpToBannerAdActivity(R.string.go_back, WorkMessageActivity.this, bannerBean, 10);

                    }


                    //老师点评或者批改作业
                } else if (type == MsgTypeConfig.MSG_WORK_EVALUATE || type == MsgTypeConfig.MSG_WORK_CORRECT) {//跳转作业详情
                    //获取本地作业详情
                    if (mLocalWorkList != null && mLocalWorkList.size() != 0) {
                        for (int i = 0; i < mLocalWorkList.size(); i++) {
                            for (int j = 0; j < mLocalWorkList.get(i).getWorkContents().size(); j++) {
                                if (mLocalWorkList.get(i).getWorkContents().get(j).getDoWorkId().equals(doWorkId)) {
                                    WorkContents workContent = mLocalWorkList.get(i).getWorkContents().get(j);
                                    jumpToNewStudyRecordH5(workContent);
                                    return;
                                }
                            }
                        }

                    } else {
                        //如果本地没有该份作业，从网上获取
                        getDoWorkInfoFromNet(doWorkId);
                    }

                } else if (type == MsgTypeConfig.MSG_WORK_CANCEL) {     //取消作业
                    Toast.makeText(WorkMessageActivity.this, "本次作业已取消", Toast.LENGTH_SHORT).show();
                    setResult(RESULT_OK);
                    finish();

                } else if (type == MsgTypeConfig.MSG_WORK_CANCEL) {//购买作业成功

                } else {
                    if (mWorkId != null && workName != null) { //跳转到作业列表
                        MsgRequest.isDelWork(mWorkId, EApplication.BRAND_ID, userInfoBase.getUserId(), senderId, new BaseCallBack() {
                            @Override
                            public void failed(int errorCode, Object data) {
                                setResult(RESULT_OK);
                                finish();
                            }

                            @Override
                            public void failed(Object data) {
                                setResult(RESULT_OK);
                                finish();
                            }

                            @Override
                            public void success(Object data) {
                                IsDelWorkBean isDelWorkBean = (IsDelWorkBean) data;
                                if (isDelWorkBean != null && isDelWorkBean.isDel) {//作业已撤回
//                                    showToastAlert("老师已撤回本次作业！");
                                    ToastUtil.INSTANCE.toastInCenter(WorkMessageActivity.this, "老师已撤回本次作业！");
                                }
                                setResult(RESULT_OK);
                                finish();
                            }

                            @Override
                            public void success(Object... data) {
                                setResult(RESULT_OK);
                                finish();
                            }
                        });

                    } else {
                        setResult(RESULT_OK);
                        finish();
                    }
                }
            }
        });

        mRefreshView.setOnHeaderRefreshListener(this);
        mRefreshView.setOnFooterRefreshListener(this);

    }

    public void onHeaderRefresh(PullToRefreshView view) {
        refreshNetData(true);
    }

    public void onFooterRefresh(PullToRefreshView view) {
        refreshNetData(false);
    }

    @Override
    protected void init() {

        if (senderName != null && !senderName.isEmpty()) {
            if (msgGroupType == MsgTypeConfig.MSG_SERVICE) {
                setTitleText("站内信");
            } else {
                setTitleText(senderName);
            }
        } else {
            setTitleText(R.string.work_msg_title);
        }
        mEApplication = (EApplication) getApplication();
        userInfoBase = mEApplication.getUserInfoBase();

        //在onPause不取消吐司
        isCancelToastOnPause = false;
    }

    @Override
    protected void loadData() {
        getLocalMyWorkDetails();
        getLocalMsgListByID();
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 获取本地数据
     */
    private void getLocalMsgListByID() {
        //正式数据入口
        SerializableManager.getInstance().deSerialize(
                SerializableManager.SerializeKey.SHARE_KEY_MSG_LIST_SENDERID + msgGroupType, new BaseCallBack() {

                    @Override
                    public void failed(int errorCode, Object data) {
                        refreshNetData(true);
                    }

                    @Override
                    public void failed(Object data) {
                        refreshNetData(true);
                    }

                    @Override
                    public void success(Object data) {
                        if (data != null) {
                            List<MessageInfo> messageInfos = (List<MessageInfo>) data;
                            workMessageAdapter.clear();
                            workMessageAdapter.addAll(messageInfos);
                        }
                        refreshNetData(true);
                    }
                }
        );

    }

    /**
     * 获取网络数据
     */
    private void getNetMsgListByID() {
        MsgDao.getInstance().getMsgsBySenderId(EApplication.BRAND_ID, userInfoBase.getUserId(), msgGroupType, curPage, LOAD_PAGE_SIZE,
                new BaseExtCallBack(WorkMessageActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                        showToastError(errorCode, data);
                        loadOver();
                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MESSAGE, data == null ? "" : "失败信息：" + data.toString(), "获取未读消息列表详情失败");

                    }

                    @Override
                    public void failed(Object data) {
                        loadOver();
                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MESSAGE, data == null ? "" : "失败信息：" + data.toString(), "获取未读消息列表详情失败");

                    }

                    @Override
                    public void success(Object data) {
                        BasePaging<MessageInfo> msgListBasePaging = (BasePaging<MessageInfo>) data;
                        ArrayList<MessageInfo> netList = (ArrayList<MessageInfo>) msgListBasePaging.getPageList();
                        refreshListData(netList);
                        loadOver();
                    }
                });

    }


    /**
     * 加载完成
     */
    private void loadOver() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isRefresh) {
                    mRefreshView.onHeaderRefreshComplete();
                } else {
                    mRefreshView.onFooterRefreshComplete();
                }
            }
        }, 500);
    }

    /**
     * 刷新网络数据(true为刷新，false为添加更多)
     *
     * @param boo
     */
    private void refreshNetData(boolean boo) {
        isRefresh = boo;
        if (isRefresh) {
            curPage = default_page;
        }
        getNetMsgListByID();
    }

    /**
     * 刷新数据
     */
    private void refreshListData(List<MessageInfo> netList) {
        if (isRefresh) {
            workMessageAdapter.clear();
        }
        curPage++;// 请求下一页
        workMessageAdapter.addAll(netList);
        if (isRefresh) {
            // 保存本地数据
            SerializableManager.getInstance().serialize(
                    SerializableManager.SerializeKey.SHARE_KEY_MSG_LIST_SENDERID + msgGroupType
                    , (Serializable) netList
            );
        }
    }

    /**
     * 获取本地作业详情
     */
    private void getLocalMyWorkDetails() {
        SerializableManager.getInstance().deSerialize(

                SerializableManager.SerializeKey.SHARE_KEY_NOTIFICATION_LIST,

                new BaseCallBack() {


                    @Override
                    public void success(Object data) {
                        if (data != null) {
                            mLocalWorkList = (List<MyWork>) data;
                        }
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                    }

                    @Override
                    public void failed(Object data) {
                    }
                });

    }


    /**
     * 设置所有消息为已查看
     */
    private void setMsgStateAllRead() {
        String brandId = EApplication.BRAND_ID + "";

    }


    private void jumpToNewStudyRecordH5(WorkContents workContent) {
        String url = EpaperConstant.URL_LSW_DETAILS;
        String pageType = "0";
        if (workContent.moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM) {
            url = EpaperConstant.URL_LSW_DETAILS;
        } else if (workContent.moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT) {
            if (workContent.getResourceType().equals(ModuleContent.ResourceType.RESOURCE_TYPE_WORD)) {
                pageType = "1";
            } else {
                pageType = "3";
            }
            url = EpaperConstant.URL_READING_REPEAD + "pageType=" + pageType + "&parentVersionId=" + workContent.parentVersionId;
        } else if (workContent.moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_ONLINE_ANSWER) {//在线作答
            pageType = "1";
            url = EpaperConstant.URL_ONLINE_PAPER_DETAIL_H5 + "pageType=" + pageType;
        }
        StringBuffer sb = new StringBuffer(url);
        sb.append("&clientId=");
        sb.append(EConstants.CLIENT_ID);
        long useeId = EApplication.getInstance().getUserInfoBase().getUserId();
        sb.append("&userId=");
        sb.append(useeId);
        sb.append("&brandId=");
        sb.append(EApplication.BRAND_ID);
        sb.append("&versionId=");
        sb.append(workContent.getVersionId());
        sb.append("&doWorkId=");
        sb.append(workContent.getDoWorkId());
        if (url.equals(EpaperConstant.URL_LSW_DETAILS)){
            sb.append("&revisedMode=1");
        }
        String title;
        try {
            title = java.net.URLEncoder.encode(workContent.getResourceName(), "UTF-8");
        } catch (Exception e) {
            title = "";
        }
        title = title.replace("+", "%20");
        sb.append("&title=");
        sb.append(title);
        sb.append("&doWorkType=0");
        MeJumpManager.jumpToStudyRecordH5Activity(ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT, this, R.string.go_back, -1, sb.toString(), workContent.getResourceName(), 0);

    }


    /**
     * 从网络上获取该份作业
     *
     * @param doWorkId
     */
    public void getDoWorkInfoFromNet(String doWorkId) {
        MsgDao.getInstance().getDoWorkInfoFromNet(doWorkId, new BaseExtCallBack(WorkMessageActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                showToastError(errorCode, data);
            }

            @Override
            public void failed(Object data) {

            }

            @Override
            public void success(Object data) {
                if (data != null) {
                    WorkContents workContents = (WorkContents) data;
                    jumpToNewStudyRecordH5(workContents);
                }
            }
        });

    }
}
